package com.hspedu.newData.dmsxl.树.二叉树的遍历.层序遍历迭代法.队列;

import com.hspedu.newData.dmsxl.ds.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-23 
 * @Version: 1.0
 */

public class LC111二叉树的最小深度 {

    public int minDepth1(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();

        queue.offer(root);

        int minDepth = 0;
        while(!queue.isEmpty()){
            int len = queue.size();
            minDepth ++;
            while(len >0){
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null){
                    return minDepth;
                }
                if (node.left != null) queue.offer(node.left);
                if (node.right!= null) queue.offer(node.right);
                len --;

            }
        }
        return 0;
    }


    // 递归法

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        if (root.left == null) {
            return rightDepth + 1;
        }
        if (root.right == null) {
            return leftDepth + 1;
        }
        return Math.min(leftDepth,rightDepth) + 1;
    }

}
